package com.mars.basic.client.controller;

import com.mars.basic.allmain.dto.AdminUserDto;
import com.mars.basic.allmain.entity.AdminUserEntity;

import com.mars.basic.allmain.po.QAdminUser;
import com.mars.basic.allmain.vo.AdminUserVo;
import com.mars.basic.client.IAdminUserClient;
import com.mars.basic.factory.AdminUserFac;
import com.mars.common.utils.*;
import com.mars.basic.service.AdminUserService;
import com.mars.common.expetion.Code;
import com.querydsl.core.types.dsl.BooleanExpression;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@RestController
public class AdminUserController implements IAdminUserClient {
    @Autowired
    private AdminUserService service;

    @Override
    public R addAdminUser(@RequestBody AdminUserVo vo) {
        QAssert.isTrue(service.checkIsExists(vo), Code.ENTITY_EXIST_EXCEPTION,"该用户以存在");
        AdminUserEntity adminUser = Beans.mapper(vo, AdminUserEntity.class);
        adminUser.setCreateTime(new Date());
        adminUser.setUpdateTime(new Date());
        adminUser.setStatus("0");
        adminUser.setPassword(PasswordUtils.encodePassword(vo.getPassword(), Constants.SALT));
        service.getAdminUserRepository().save(adminUser);
        AdminUserEntity one = service.getAdminUserRepository().findOneIfMutil(QAdminUser.adminUser.name.eq(adminUser.getName()));
        return R.data(one);
    }

    @Override
    public R getList() {
        BooleanExpression where = AnyWhereConditionPath.anyWherePredicate();
        List<AdminUserEntity> all = service.getAdminUserRepository().findAll(where);
        List<AdminUserDto> list = all.stream().map(AdminUserFac::toDto).collect(Collectors.toList());
        return R.data(list);
    }

    @Override
    public R updateAdminUser(@RequestBody AdminUserVo vo) {
        AdminUserEntity adminUser = Beans.mapper(vo, AdminUserEntity.class);
        adminUser.setUpdateTime(new Date());
        adminUser.setPassword(PasswordUtils.encodePassword(vo.getPassword(), Constants.SALT));
        service.getAdminUserRepository().save(adminUser);
        service.getAdminUserRepository().findOneIfMutil(QAdminUser.adminUser.name.eq(adminUser.getName()));
        return R.ok();
    }
}
